package com.anli.leguansuo;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/9  9:04
 * 描述: 以锁库存的场景讲解乐观锁
 */

@Component
public class LeGuanSuoService {

   @Autowired
   private LeGuanStockDao leGuanStockDao;

    @Autowired
    private RedisTemplate<String,Object> myRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
   /**
    * 作者: LCG
    * 日期: 2021/3/9  9:15
    * 描述: 商品的id，  锁定的库存量
    * @Param [goodsId, lockStock]
    * @Return void
    */
   public void updateStock(String goodsId,int lockStock){
       Map<String, Object> goodsStock = leGuanStockDao.getGooodsById(goodsId);
       //if条件成立的话表示库存充足
       if(Long.valueOf(goodsStock.get("stock").toString())>=lockStock){
            Map<String,Object> parm=new HashMap<>();
            parm.put("goodsId",goodsId);
            parm.put("version",goodsStock.get("version"));
            parm.put("stock",Long.valueOf(goodsStock.get("stock").toString())-lockStock);

            //更新库存
           int updateStock = leGuanStockDao.updateStock(parm);
           //System.out.println("=====更新结果===="+updateStock);
           //更新成功
           if(updateStock==1){
               System.out.println("============更新成功==库存减去-"+lockStock);
           }else{
               System.out.println("============更新失败==加入定时任务");
               Map<String,Object> parm2=new HashMap<>();
               parm2.put("goodsId",goodsId);
               parm2.put("lockStock",lockStock);
               //使用加入redis的队列
               String string = JSON.toJSONString(parm2);
               //插入定时任务表
               leGuanStockDao.insertTask(parm2);

               //采用消息队列
               //rabbitTemplate.convertAndSend("","redis-key",string);
           }
       }else{
           //库存不足 则挂起订单等待补货
       }


   }


}
